package com.itboye.eweilisten.me.home;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;

import com.itboye.eweilisten.R;
import com.itboye.eweilisten.app.MyApplication;
import com.itboye.eweilisten.util.network.NetState;
import com.itboye.eweilisten.util.network.NetWorkUtil;
import com.itboye.eweilisten.util.network.TipsToast;
import com.itboye.eweilisten.util.network.UISwitchButton;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class NetWorkActivity extends Activity implements OnClickListener {
	private final String TAG = "MPermissions";   //获取权限
	private int REQUEST_CODE_PERMISSION = 0x00099;//获取权限

	private UISwitchButton switchWifi, switchGprs;
	ConnectivityManager mConnectivityManager;
	ImageView img_gprs, img_wifi;
	private static TipsToast tipsToast;
	Intent intent;
	Button but_close;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_network);
		requestPermission(new String[]{Manifest.permission.MODIFY_PHONE_STATE}, 0x0002);
		switchWifi = (UISwitchButton) findViewById(R.id.switch_wifi);
		switchGprs = (UISwitchButton) findViewById(R.id.switch_liuliang);

		img_gprs = (ImageView) findViewById(R.id.img_gprs);
		img_wifi = (ImageView) findViewById(R.id.img_wifi);

		but_close = (Button) findViewById(R.id.but_close);
		but_close.setOnClickListener(this);

		switchWifi.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					toggleWiFi(true);
					img_wifi.setBackgroundResource(R.drawable.wuxianlanse);
					showTips(R.drawable.tips_smile, "正在打开WiFi网络...");
				} else {
					toggleWiFi(false);
					img_wifi.setBackgroundResource(R.drawable.wuxian1);
					showTips(R.drawable.tips_smile, "正在关闭WiFi网络...");
				}
			}
		});

		switchGprs.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				Log.d("=====banben===",android.os.Build.VERSION.RELEASE.toString().substring(0,1)+"");

				if (isChecked) {
					if(Integer.parseInt(android.os.Build.VERSION.RELEASE.toString().substring(0,1)+"")<5){
						setMobileNetEnable();
					}else {
                        setMobileDataState(getApplication(),true);
					}
					img_gprs.setBackgroundResource(R.drawable.wuxianerlans);
					showTips(R.drawable.tips_smile, "正在打开数据网络...");
				} else {
					if(Integer.parseInt(android.os.Build.VERSION.RELEASE.toString().substring(0,1)+"")<5){
						setMobileNetUnable();
					}else {
                    setMobileDataState(getApplication(),false);
					}

					showTips(R.drawable.tips_smile, "正在关闭数据网络...");
					img_gprs.setBackgroundResource(R.drawable.wuxianer);
				}
			}
		});

	}

	/**
	 * 设置是否启用WIFI网络
	 */
	public void toggleWiFi(boolean status) {
		WifiManager wifiManager = (WifiManager) MyApplication.instance
				.getSystemService(Context.WIFI_SERVICE);
		if (status == true && !wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);

		} else if (status == false && wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(false);
		}
	}

	/**
	 * 设置启用数据流量
	 */
	public final void setMobileNetEnable() {

		mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		Object[] arg = null;
		try {
			boolean isMobileDataEnable = invokeMethod("getMobileDataEnabled",
					arg);
			if (!isMobileDataEnable) {
				invokeBooleanArgMethod("setMobileDataEnabled", true);

			}
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	/**
	 * 设置不启用数据流量
	 */
	public final void setMobileNetUnable() {
		mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		Object[] arg = null;
		try {
			boolean isMobileDataEnable = invokeMethod("getMobileDataEnabled",
					arg);
			if (isMobileDataEnable) {
				invokeBooleanArgMethod("setMobileDataEnabled", false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setMobileDataState(Context cxt, boolean mobileDataEnabled) {
		TelephonyManager telephonyService = (TelephonyManager) cxt.getSystemService(Context.TELEPHONY_SERVICE);
		try {
			Method setMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
			if (null != setMobileDataEnabledMethod)
			{
				setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled);
			}
		}
		catch (Exception e) {
			Log.d("setMobileDataState", "Error setting" + ((InvocationTargetException)e).getTargetException() + telephonyService);
		}
	}

	public boolean getMobileDataState(Context cxt) {
		TelephonyManager telephonyService = (TelephonyManager) cxt.getSystemService(Context.TELEPHONY_SERVICE);
		try {
			Method getMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("getDataEnabled");
			if (null != getMobileDataEnabledMethod)
			{
				boolean mobileDataEnabled = (Boolean) getMobileDataEnabledMethod.invoke(telephonyService);
				return mobileDataEnabled;
			}
		}
		catch (Exception e) {
			Log.d("setMobileDataState", "Error getting" + ((InvocationTargetException)e).getTargetException() + telephonyService);
		}

		return false;
	}



	public boolean invokeMethod(String methodName, Object[] arg)
			throws Exception {

		ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		Class ownerClass = mConnectivityManager.getClass();

		Class[] argsClass = null;
		if (arg != null) {
			argsClass = new Class[1];
			argsClass[0] = arg.getClass();
		}

		Method method = ownerClass.getMethod(methodName, argsClass);

		Boolean isOpen = (Boolean) method.invoke(mConnectivityManager, arg);

		return isOpen;
	}

	public Object invokeBooleanArgMethod(String methodName, boolean value)
			throws Exception {

		ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		Class ownerClass = mConnectivityManager.getClass();

		Class[] argsClass = new Class[1];
		argsClass[0] = boolean.class;

		Method method = ownerClass.getMethod(methodName, argsClass);

		return method.invoke(mConnectivityManager, value);
	}

	/**
	 * 自定义taost
	 * 
	 * @param iconResId
	 *            图片
	 */
	private void showTips(int iconResId, String tips) {
		if (tipsToast != null) {
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
				tipsToast.cancel();
			}
		} else {
			tipsToast = TipsToast.makeText(getApplication().getBaseContext(),
					tips, TipsToast.LENGTH_LONG);
		}
		tipsToast.show();
		tipsToast.setIcon(iconResId);
		tipsToast.setText(tips);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.but_close:// 关闭的同时判断网络状态
			int type = NetWorkUtil.getAPNType(NetWorkActivity.this);
			intent = new Intent();
			intent.putExtra("key", type + ""); // 设置要发送的数据
			setResult(RESULT_OK, intent);
			this.finish();
			break;
		}
	}

	@SuppressWarnings("static-access")
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == event.KEYCODE_BACK) {// 返回的同时判断网络状态
			int type = NetWorkUtil.getAPNType(NetWorkActivity.this);
			intent = new Intent();
			intent.putExtra("key", type + ""); // 设置要发送的数据
			setResult(RESULT_OK, intent);
			this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		NetState.IS_ENABLE = true;// Activity销毁的时候允许启用跳转
	}



	/**
	 * 请求权限
	 *
	 * @param permissions 请求的权限
	 * @param requestCode 请求权限的请求码
	 */
	public void requestPermission(String[] permissions, int requestCode) {
		this.REQUEST_CODE_PERMISSION = requestCode;
		if (checkPermissions(permissions)) {
			permissionSuccess(REQUEST_CODE_PERMISSION);
		} else {
			List<String> needPermissions = getDeniedPermissions(permissions);
			ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_PERMISSION);
		}
	}

	/**
	 * 检测所有的权限是否都已授权
	 *
	 * @param permissions
	 * @return
	 */
	private boolean checkPermissions(String[] permissions) {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
			return true;
		}

		for (String permission : permissions) {
			if (ContextCompat.checkSelfPermission(this, permission) !=
					PackageManager.PERMISSION_GRANTED) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 获取权限集中需要申请权限的列表
	 *
	 * @param permissions
	 * @return
	 */
	private List<String> getDeniedPermissions(String[] permissions) {
		List<String> needRequestPermissionList = new ArrayList<>();
		for (String permission : permissions) {
			if (ContextCompat.checkSelfPermission(this, permission) !=
					PackageManager.PERMISSION_GRANTED ||
					ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
				needRequestPermissionList.add(permission);
			}
		}
		return needRequestPermissionList;
	}


	/**
	 * 系统请求权限回调
	 *
	 * @param requestCode
	 * @param permissions
	 * @param grantResults
	 */
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (requestCode == REQUEST_CODE_PERMISSION) {
			if (verifyPermissions(grantResults)) {
				permissionSuccess(REQUEST_CODE_PERMISSION);
				if(permissions[0].equals(Manifest.permission.MODIFY_PHONE_STATE)){
//					MyApplication.getInstance().initLocation();
					Log.d("=====shouquan==","111111");
				}

			} else {
				permissionFail(REQUEST_CODE_PERMISSION);
				showTipsDialog();

			}
		}
	}

	/**
	 * 确认所有的权限是否都已授权
	 *
	 * @param grantResults
	 * @return
	 */
	private boolean verifyPermissions(int[] grantResults) {
		for (int grantResult : grantResults) {
			if (grantResult != PackageManager.PERMISSION_GRANTED) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 显示提示对话框
	 */
	private void showTipsDialog() {
		new AlertDialog.Builder(this)
				.setTitle("提示信息")
				.setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				})
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						startAppSettings();
					}
				}).show();
	}

	/**
	 * 启动当前应用设置页面
	 */
	private void startAppSettings() {
		Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
//		intent.setData(Uri.parse("package:" + getPackageName()));
		startActivity(intent);
	}

	/**
	 * 获取权限成功
	 *
	 * @param requestCode
	 */
	public void permissionSuccess(int requestCode) {
		Log.d(TAG, "获取权限成功=" + requestCode);

	}

	/**
	 * 权限获取失败
	 * @param requestCode
	 */
	public void permissionFail(int requestCode) {
		Log.d(TAG, "获取权限失败=" + requestCode);
	}



}
